package com.tron.dobest.netty.socket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.channel.ChannelHandler.Sharable;

/**
 * 描述：处理http请求，如果是/ws结尾的url连接，升级为websocket协议，之后的消息以websocket协议发送
 *
 * @author TRON
 * @since 2020-06-18
 */
@Sharable
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private String wsUrl;

    public HttpRequestHandler(String wsUrl) {
        this.wsUrl = wsUrl;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        System.out.println("===接收到http请求===");
        if (request.uri().contains(wsUrl)) {
            String uri = request.uri();
            System.out.println("===升级"+uri+"请求===");
            request.setUri(wsUrl);
            System.out.println("===握手请求通道Id："+ctx.channel().id().asLongText()+"===");
            //调用下一个处理器的read方法，request.retain() 增加应用计数保留连接
            ctx.fireChannelRead(request.retain());
        }
    }
}
